<?php
$loader->requireOnce('includes/inPatientCore/InPatientCoreErrorCode.class.php');
$loader->requireOnce('includes/inPatientCore/InPatientCoreException.class.php');
$loader->requireOnce('includes/CoreErrorCode.class.php');
$loader->requireOnce('includes/CoreException.class.php');
$loader->requireOnce('includes/EnumerationConstant.class.php');
$loader->requireOnce('includes/CommonConstant.class.php');
$loader->requireOnce('includes/EmerQueueFactory.class.php');
$loader->requireOnce('includes/EmergencyInstantPanel.class.php');

$loader->requireOnce('includes/EmerProcessor.class.php');



/**
 * Controler for Emergency queues.<br>
 * most of action on emergency queues happen here.
 * @package module.controllers
 * @author viethd
 * @version $Id$
 * @copyright 2009 LHV Company
 */
class C_EmergencyInPatient extends Controller {
	private $logger ;
	private $tpProcessor ;
	function __construct($template_mod = "general") {
		parent::Controller();
		if (Celini::getCurrentController() == 'EmergencyInPatient') {
			$menu =& Menu::getInstance();
			$menu->currentSection = 'patient';
		}
		$this->logger = LoggerManager::getLogger('core.controllers.C_EmergencyInPatient');
		$this->template_mod = $template_mod;
		$this->view->path="emergency_inpatient";
		$this->tpProcessor = new EmerProcessor($this);
		$icd10 = new Icd10Selector();
		$icd10->initIcd10ForController($this,1);        
	}
	/**
	 * Display emergency queue.
	 * @return html page for emergency department doctor queues
	 */
	public function actionRenderDoctorQueues() {
		$this->assign('today', L10nHelper::renderDateTime(date('Y-m-d'), L10nHelper::DATE_FULL, 'date'));
		$patientNumber = Celini::newORDO('InPatient')->countPatientNumber($this->_me->get_department_id());		
		$this->assign('patientNumber', $patientNumber);
		return $this->view->render('doctor.html');
	}

	public function actionTestCheckIn() {
	 try {
	 	$this->tpProcessor->checkInPatient("1021187",$this->_me->get_department_id(),date('Y-m-d H:i:s'),
	 	CommonConstant::IN_PATIENT,
	 	EnumerationConstant::PATIENT_SUB_STATUS_EMER_EMERGENCY);
	 } catch (InpatientCoreException $ex) {
	 	echo InPatientCoreErrorCode::getErrorMess($ex->getErrorCode());
	 }
	}

	/**
	 * build ui for emergency and recovery queues.
	 * @return jsonobject
	 * <br>
	 * data.emergency content of emergency queue <br>
	 * data.recovery content of recovery queue <br>
	 */
	public function actionRenderDoctorQueuesAjax() {
		$result = array();
		$result['emergency'] = $this->renderEmergencyQueue();
		$result['recovery'] = $this->renderRecoveryQueue();
		// Fix bug 934: After checked out, patient's number in queue page has not updated
		$patientNumber = Celini::newORDO('InPatient')->countPatientNumber($this->_me->get_department_id());       
        $result['patientNumber'] = $patientNumber;
		return json_encode($result);
			
	}
	
	/**
	 * Change status of patient has [ticket id] from <br>
	 * emergency to recovery
	 * @param $_GET['ticketId']
	 * @return data <br>
	 * data.error.code != null if got error. <br>
	 * data.error.mess == null if successful. <br>
	 */
	public function actionMoveToRecoveryAjax() {

		$data = array('error'=>array('code'=>0,'mess'=>''));
		$ticketId = $_GET['ticketId'];
		$this->logger->info('Start move to recovery room for patient has ticket ['. $tickId .']');
		try {
			
			$this->tpProcessor->changeCheckinPatientItemStatus($ticketId,
			EnumerationConstant::PATIENT_SUB_STATUS_EMER_RECOVERY);
			$inPatientTicketMg = Celini::newORDO("InPatientTicket");
            $ticketObj = $inPatientTicketMg->getTicketInfo($ticketId);
			$statusRecover = Utils::getEnumKey(EnumerationConstant::PATIENT_SUB_STATUS, EnumerationConstant::PATIENT_SUB_STATUS_EMER_RECOVERY);
			PatientTransferHistory::record($ticketId, $this->_me->get_department_id(), $ticketObj['patient_id'], CommonConstant::IN_PATIENT,
            CommonConstant::ACTION_RECORD_STATUS, $statusRecover, date('Y-m-d H:i:s'));
		} catch (InpatientCoreException $ex) {
			$result['error']['code'] = $ex->getErrorCode();
			$result['error']['mess'] = InPatientCoreErrorCode::getErrorMess($ex->getErrorCode());
			$this->logger->error('Move to recovery room for ticket [' . $tickId . '] fail. Error detail: '. $ex->getMessage());
		} catch (EnumException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = CoreErrorCode::getErrorMess($ex->getErrorCode());
            $this->logger->error('Move to recovery room for ticket [' . $tickId . '] fail. Error detail: '. $ex->getMessage());
        }
		$this->logger->info('Finish move to recovery room for patient has ticket ['. $tickId .']');

		return json_encode($data);
	}
	/**
	 *
	 * process check out for leaving.
	 *
	 * @param $_GET['ticketId']
	 * @param $_GET['enumTreatmentResult'];
	 * @return
	 * array('error'=>array('code'=>[error code],'mess'=>[error mess]));
	 */
	public function actionCheckOutLeaveAjax() {
		$result = array('error'=>array('code'=>0,'mess'=>''),'result'=>'');
		$tickId = $_GET['ticketId'];
		$enumTreatmentResult = $_GET['enumTreatmentResult'];
		$this->logger->info('Start check out leave for patient has ticket ['. $tickId .']');
		try {
			//save emr info
			$this->tpProcessor->emerRecordEmrInfoCOLeave($tickId, $enumTreatmentResult);
			//do check out
			$result['result']=
			$this->tpProcessor->checkOutLeave($tickId,
			CommonConstant::IN_PATIENT,
			date('Y-m-d H:i:s'));
				
		} catch (InpatientCoreException $ex) {
			$result['error']['code'] = $ex->getErrorCode();
			$result['error']['mess'] = InPatientCoreErrorCode::getErrorMess($ex->getErrorCode());
			$this->logger->error('Check-out for ticket [' . $tickId . '] fail. Error detail: '. $ex->getMessage());
		} catch (EnumException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = CoreErrorCode::getErrorMess($ex->getErrorCode());
            $this->logger->error('Check-out for ticket [' . $tickId . '] fail. Error detail: '. $ex->getMessage());
        }

		$this->logger->info('End check out leave for patient has ticket ['. $tickId .']');
		return json_encode($result);
	}
	/**
	 *
	 * Display check out leave form.
	 *
	 * @param $_GET['ticketId']
	 * @return
	 * array('error'=>array('code'=>[error code],'mess'=>[error mess]),'result'=>'check out form');
	 */
	public function actionDisplayCheckOutLeaveAjax() {
		$result = array('error'=>array('code'=>0,'mess'=>''),'result'=>'');
		$tickId = $_GET['ticketId'];
		$this->logger->info('Start Display check out leave form for patient has ticket ['. $tickId .']');

		$departmentId = $this->_me->get_department_id();
		if ($this->tpProcessor->canCheckOut($tickId) == true) {
			//can check out
			$result['result']= $this->tpProcessor->buildCheckOutLeaveHtmlForm($tickId, $departmentId);
		} else {
			//can not check out
			//TODO define code and mess
			$result['error']['code'] = 1;
			$result['error']['mess'] = L10nHelper::_("Cannot checkout");
		}

		$this->logger->info('End Display check out leave form for patient has ticket ['. $tickId .']');
		return json_encode($result);
	}
	/**
	 *
	 * Display check out death form.
	 *
	 * @param $_GET['ticketId']
	 * @return
	 * array('error'=>array('code'=>[error code],'mess'=>[error mess]),'result'=>'check out form');
	 */
	public function actionCheckOutDeathAjax() {
		$result = array('error'=>array('code'=>0,'mess'=>''),'result'=>'', 'deathInsideInfoId'=>'');
		$tickId = $_GET['ticketId'];
		$this->logger->info('Start check out death for patient has ticket ['. $tickId .']');
		try {
			$result['deathInsideInfoId'] = $this->saveReportDeadInsideInfo();
			$result['result']= $this->tpProcessor->checkOutDeath($tickId, CommonConstant::IN_PATIENT, date('Y-m-d H:i:s'));
		} catch (InpatientCoreException $ex) {
			$result['error']['code'] = $ex->getErrorCode();
			$result['error']['mess'] = InPatientCoreErrorCode::getErrorMess($ex->getErrorCode());
			$this->logger->error('Check-out for ticket [' . $tickId . '] fail. Error detail: '. $ex->getMessage());
		} catch (EnumException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = CoreErrorCode::getErrorMess($ex->getErrorCode());
            $this->logger->error('Check-out for ticket [' . $tickId . '] fail. Error detail: '. $ex->getMessage());
        }

		$this->logger->info('Finish check out death for patient has ticket ['. $tickId .']');
		return json_encode($result);
	}
    private function saveReportDeadInsideInfo($deathInfoId = 0){
        if(isset($_GET['deathInfoIdHdn'])){
            $deathInfoId  =   $_GET['deathInfoIdHdn'];
        }
        $objDeathInfo  =   Celini::newORDO('DeathInsideInfo', $deathInfoId);
        if (isset($_GET['patientIdHdn'])){
            $patientId =   $_GET['patientIdHdn'];
        }
        else {
            $patientId =   $objDeathInfo->getPatientId();
        }
        $objPerson  =   Celini::newORDO('Person', $patientId);
        $addId      =   $objPerson->getAddressId();
        $objAddress =   Celini::newORDO('Address', $addId);

        // Address object
        $address    =   Utils::sanitizeAndCaseTitle($_GET['addressTxt']);
        $provinceId =   $_GET['provinceLbx'];
        $districtId =   $_GET['districtLbx'];
        $wardName   =   $_GET['wardNameTxt'];
        $addressData = array(
            'street'        =>  $address,
            'province_id'   =>  $provinceId,
            'district_id'   =>  $districtId,
            'ward_name'     =>  $wardName);
        $objAddress->populateArray($addressData);
        $objAddress->persist();

        // Person object
        $dates['year']  =   (int)Utils::sanitizeText($_GET['DOB_yyyy']);
        $dates['month'] =   (int)Utils::sanitizeText($_GET['DOB_mm']);
        $dates['day']   =   (int)Utils::sanitizeText($_GET['DOB_dd']);
        $name   =   Utils::sanitizeAndCaseTitle($_GET['patientNameTxt']);
        $career =   $_GET['careerLbx'];
        $personData = array(
            'name'      =>  $name,
            'career_id' =>  $career,
            'date_of_birth' =>  L10nHelper::getISODate($dates)
        );
        
        $objPerson->populateArray($personData);
        $objPerson->persist();

        // DeathInsideInfo object
        $conclusion     =   Utils::sanitizeText($_GET['mediProcessTxt']);
        //$doctorId		=   $_GET['doctorLbx'];
        $checkInTime['year']   =   Utils::sanitizeText($_GET['checkIn_yyyy']);
        $checkInTime['month']  =   Utils::sanitizeText($_GET['checkIn_mm']);
        $checkInTime['day']    =   Utils::sanitizeText($_GET['checkIn_dd']);
        $timeCheckIn    =   L10nHelper::getISODate($checkInTime) . " " . Utils::sanitizeText($_GET['checkInTimeTxt']);
        
        $deathTime['year']   =   Utils::sanitizeText($_GET['death_yyyy']);
        $deathTime['month']  =   Utils::sanitizeText($_GET['death_mm']);
        $deathTime['day']    =   Utils::sanitizeText($_GET['death_dd']);
        $timeDeath    =   L10nHelper::getISODate($deathTime) . " " . Utils::sanitizeText($_GET['deathTimeTxt']);
        
        $checkOutDeathTime['year'] =   Utils::sanitizeText($_GET['checkOutDeath_yyyy']);
        $checkOutDeathTime['month']=   Utils::sanitizeText($_GET['checkOutDeath_mm']);
        $checkOutDeathTime['day']  =   Utils::sanitizeText($_GET['checkOutDeath_dd']);
        $timeCheckOutDeath	=	L10nHelper::getISODate($checkOutDeathTime) . " " . Utils::sanitizeText($_GET['checkOutDeathTimeTxt']);
        
        $deathInfo	=	array(
				 'patient_id'			=> $patientId,
				 'department_id'		=> $_GET['departmentIdHdn'],
				 'check_in_time'		=> $timeCheckIn,
				 'death_time'			=> $timeDeath,
				 'check_out_death_time'	=> $timeCheckOutDeath,
			     'preside'				=> Utils::sanitizeText($_GET['presideTxt']),
			     'secretary'			=> Utils::sanitizeText($_GET['secretaryTxt']),
			     'participants'			=> Utils::sanitizeText($_GET['participantTxt']),
			     'medication_process'	=> Utils::sanitizeText($_GET['medicaTxt']),
			     'conclusion'			=> Utils::sanitizeText($_GET['conclusionTxt'])
        );
        $objDeathInfo->populateArray($deathInfo);
        $objDeathInfo->persist();

        return  $objDeathInfo->get_id();         
    }
	/**
	 *
	 * Display check out death form.
	 *
	 * @param $_GET['ticketId']
	 * @return
	 * array('error'=>array('code'=>[error code],'mess'=>[error mess]),'result'=>'check out form');
	 */
	public function actionDisplayCheckOutDeathAjax() {
		$result = array('error'=>array('code'=>0,'mess'=>''),'result'=>'');
		$tickId = $_GET['ticketId'];
		$departmentId = $this->_me->get_department_id();
		if ($this->tpProcessor->canCheckOut($tickId) == true) {
			//can check out
			$result['result']= $this->tpProcessor->buildCheckOutDeathHtmlForm($tickId, $departmentId);
		} else {
			//can not check out
			//TODO define code and mess
			$result['result']['code'] = 1;
			$result['result']['mess'] = "Cannot checkout";
		}

		return json_encode($result);
	}
	/**
	 *
	 * process check out change department.
	 *
	 * @param $_GET['ticketId']
	 * @param $_GET['toDepartmentId']
	 * @return
	 * array('error'=>array('code'=>[error code],'mess'=>[error mess]));
	 */
	public function actionCheckOutChangeDepartmentAjax() {
		$result = array('error'=>array('code'=>0,'mess'=>''),'result'=>'');
		$tickId = $_GET['ticketId'];
		$toDepartmentId = $_GET['toDepartmentId'];
		$enumTreatmentResult = $_GET['enumTreatmentResult'];
		$this->logger->info('Start check out change department for patient has ticket ['. $tickId .']');
		try {
			$this->tpProcessor->emerRecordEmrInfoCOChangeDept($tickId, $enumTreatmentResult);
			$result['result']= $this->tpProcessor->checkOutchangeDepartment($tickId,
			CommonConstant::IN_PATIENT,
			date('Y-m-d H:i:s'),
			$toDepartmentId,
			EnumerationConstant::PATIENT_SUB_STATUS_EMER_EMERGENCY);
		} catch (InpatientCoreException $ex) {
			$result['error']['code'] = $ex->getErrorCode();
			$result['error']['mess'] = InPatientCoreErrorCode::getErrorMess($ex->getErrorCode());
			$this->logger->error('Check-out for ticket [' . $tickId . '] fail. Error detail: '. $ex->getMessage());
		} catch (EnumException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = CoreErrorCode::getErrorMess($ex->getErrorCode());
            $this->logger->error('Check-out for ticket [' . $tickId . '] fail. Error detail: '. $ex->getMessage());
        }

		$this->logger->info('Finish check out change department for patient has ticket ['. $tickId .']');
		return json_encode($result);
	}
	/**
	 *
	 * Display check out (change dept) form.
	 *
	 * @param $_GET['ticketId']
	 * @return
	 * array('error'=>array('code'=>[error code],'mess'=>[error mess]),'result'=>'check out form');
	 */
	public function actionDisplayCheckOutDeptAjax() {
		$result = array('error'=>array('code'=>0,'mess'=>''),'result'=>'');
		$tickId = $_GET['ticketId'];
		$currentDepartmentId = $this->_me->get_department_id();
		if ($this->tpProcessor->canCheckOut($tickId) == true) {
			//can check out
			$result['result']= $this->tpProcessor->buildCheckOutChangeDeptHtmlForm($tickId, $currentDepartmentId);
		} else {
			//can not check out
			//TODO define code and mess
			$result['result']['code'] = 1;
			$result['result']['mess'] = "Cannot checkout";
		}

		return json_encode($result);
	}

	/**
	 * build emergency queue
	 * @return html body of emergency queue
	 */
	private function renderEmergencyQueue() {
		$queue = EmerQueueFactory::getQueue(EmerQueueFactory::DOCTOR);
			
		return $queue->renderQueueAjax($this->_me->get_department_id(),
		EnumerationConstant::PATIENT_SUB_STATUS_EMER_EMERGENCY);

	}

	/**
	 * build emergency queue
	 * @return html body of emergency queue
	 */
	private function renderRecoveryQueue() {
		$queue = EmerQueueFactory::getQueue(EmerQueueFactory::DOCTOR);
			
		return $queue->renderQueueAjax($this->_me->get_department_id(),
		EnumerationConstant::PATIENT_SUB_STATUS_EMER_RECOVERY);

	}
}
?>